package com.tywj.lib.businessweak.list

import androidx.collection.ArrayMap
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.tywj.lib.businessweak.entity.AbsLoadList
import com.tywj.lib.businessweak.view.IBaseView
import com.tywj.lib.businessweak.widget.IStatusLayout
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.loadmore.LoadMoreView
import com.tywj.lib.core.common.util.LogUtil

/**
 * <pre>
 *     author : June Yang
 *     time   : 2020/05/12
 *     desc   : 刷新和加载更多帮助类
 *     version: 1.0.0
 * </pre>
 */
@Deprecated(
    "该类被废弃了",
    ReplaceWith("PagingHelper", "xxx.businessweak.paging.PagingHelper")
)
class RefreshAndLoadMoreHelper<D : AbsLoadList<T>, T>(
    private val swipeRefreshLayout: SwipeRefreshLayout,
    private val statusLayout: IStatusLayout,
    private val recycleList: RecyclerView,
    private val adapter: BaseQuickAdapter<T, *>,
    private val listImpl: IList<D, T>,
    private val loadMoreView: LoadMoreView,
    private val baseView: IBaseView
) {

    // 下拉刷新是否可用
    var isRefreshEnabled = true
        set(value) {
            swipeRefreshLayout.isEnabled = value
            field = value
        }

    // 请求参数
    private var requestParamMap = ArrayMap<String, String>()
    // 当前请求的数据
    private var currentData: D? = null
    // 是否显示加载完成布局
    private var loadEndViewVisible = true

    init {
        initListener()
    }

    fun refresh() {
        if (adapter.data.isEmpty()) {
            // 如果刷新的时候，数据集合为空，显示加载中布局
            statusLayout.showLoadingLayout()
        }
        // 刷新请求参数
        requestParamMap = listImpl.getRequestParams()

        val request = listImpl.getRequest()
        for (item in requestParamMap) {
            request.param(item.key, item.value)
        }

        listImpl.executeRequest(request.attachToLifecycle(baseView.getLifecycleOwner()), {
            currentData = it
            if (it.list.isEmpty()) {
                // 刷新完，数据集合为空，显示内容为空布局
                listImpl.onLoadSuccess(true, it)
                statusLayout.showEmptyLayout()
            } else {
                if (!listImpl.onLoadSuccess(true, it)) {
                    // 子类不处理
                    recycleList.post { adapter.setNewData(it.list) }
                }
                statusLayout.showContentLayout()
                if (it.nextPage == -1) {
                    // 下一页地址为空，没有更多的数据了
                    loadMoreEnd()
                }
            }
        }, { code, message ->
            // 判断子类是否处理这个错误
            if (listImpl.onLoadError(true, code, message)) {
                return@executeRequest
            }

            if (adapter.data.size > 0) {
                // 如果旧数据不为空，则只是提示刷新失败
                baseView.shortToast(message)
            } else {
                // 没有旧数据，显示加载失败布局
                statusLayout.showErrorLayoutByCode(code, message)
            }
        }, {
            refreshComplete()
        })
    }

    fun loadMore() {
        if (currentData == null || currentData!!.nextPage == -1) {
            // 第一页数据没有加载出来或者没有下一页数据
            return
        }

        val request = listImpl.getRequest()
        for (item in requestParamMap) {
            request.param(item.key, item.value)
        }
        request.param("page", currentData!!.nextPage.toString())
            .param("requestTime", currentData!!.requestTime.toString())

        listImpl.executeRequest(request.attachToLifecycle(baseView.getLifecycleOwner()), {
            currentData = it
            if (it.list.isEmpty()) {
                // 获取的数据集合为空，说明没有更多的数据了
                listImpl.onLoadSuccess(false, it)
                loadMoreEnd()
            } else {
                if (!listImpl.onLoadSuccess(false, it)) {
                    // 子类不处理
                    recycleList.post { adapter.addData(it.list) }
                }
                if (it.nextPage == -1) {
                    // 下一页地址为空，没有更多的数据了
                    loadMoreEnd()
                } else {
                    // 还有下一页数据，本次加载完成
                    loadMoreComplete()
                }
            }
        }, { code, message ->
            // 判断子类是否处理这个错误
            if (listImpl.onLoadError(false, code, message)) {
                return@executeRequest
            }

            loadMoreFail()
        }, {
            // do nothing
        })
    }

    fun setLoadEndViewVisible(visible: Boolean) {
        loadEndViewVisible = visible
    }

    private fun initListener() {
        // 下拉刷新监听
        swipeRefreshLayout.setOnRefreshListener {
            // 禁用上拉加载更多
            adapter.setEnableLoadMore(false)
            // 调用下拉刷新
            refresh()
        }

        // 设置加载更多时显示的布局
        adapter.setLoadMoreView(loadMoreView)

        // 加载更多监听
        adapter.disableLoadMoreIfNotFullPage(recycleList)
        adapter.setOnLoadMoreListener({
            // 禁用下拉刷新
            swipeRefreshLayout.isEnabled = false
            // 调用上拉加载更多
            loadMore()
        }, recycleList)
    }

    private fun refreshComplete() {
        LogUtil.d("refreshComplete")
        recycleList.post {
            // 下拉刷新完成
            swipeRefreshLayout.isRefreshing = false
            // 开启上拉加载更多
            adapter.setEnableLoadMore(true)
        }
    }

    private fun loadMoreComplete() {
        LogUtil.d("loadMoreComplete")
        recycleList.post {
            // 开启下拉刷新
            swipeRefreshLayout.isEnabled = isRefreshEnabled
            // 上拉加载更多完成
            adapter.loadMoreComplete()
        }
    }

    /**
     * 上拉加载更多结束（没有更多的数据了）
     */
    private fun loadMoreEnd() {
        LogUtil.d("loadMoreEnd")
        recycleList.post {
            // 开启下拉刷新
            swipeRefreshLayout.isEnabled = isRefreshEnabled
            adapter.loadMoreEnd(!loadEndViewVisible)
        }
    }

    private fun loadMoreFail() {
        LogUtil.d("loadMoreFail")
        recycleList.post {
            // 开启下拉刷新
            swipeRefreshLayout.isEnabled = isRefreshEnabled
            // 上拉加载更多失败
            adapter.loadMoreFail()
        }
    }
}